// pages/map/map.js
const app = getApp();

let req = require('../../utils/request.js');
let api = require('../../utils/api.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    motto: 'Hello World',
    wd: '',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    focus: false,
    placeholder: '查询景点',
    display: 'none',
    scale: 14,
    picker_values: [],
    picker_checked: '正在定位'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.listAllCity();
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    var _this = this, user_token = wx.getStorageSync('user_token');

    wx.showLoading({
      title: '加载附近景点',
    })

    //获取用户设备数据
    wx.getSystemInfo({
      success: function (data) {
        _this.setData({ mediaInfo: data });
      }
    });

    user_token && req.request(api.getUserEditableInfo, { data: { token: user_token } }, function (res) {
      res = res.data
      let custom = res;
      if(custom) {
        custom.country = !custom.country ? 'Andorra' : custom.country
        custom.code = !custom.code ? 'AD' : custom.code
        custom.area = !custom.area ? '376' : custom.area
        custom.firstName = custom.firstname
        custom.fullName = custom.fullname
        custom.lastName = custom.lastname
        custom.token = user_token
        delete (custom.firstname)
        delete (custom.fullname)
        delete (custom.lastname);

        wx.setStorageSync('custom', custom);
      }
    })

    //获取用户位置
    wx.getLocation({
      type: 'gcj02',
      success: function(res) {
        //根据用户位置获取周围10公里范围内的商户
        var lng = res.longitude,
            lat = res.latitude

        //将地图基本信息赋值到Page对象
        _this.setData({
          longitude: lng,
          latitude: lat,
          controls: [{
            id: 1,
            iconPath: '/images/person.png',
            position: {
              left: _this.data.mediaInfo.screenWidth - 60,
              top: _this.data.mediaInfo.screenHeight / 2 - 100 - 30,
              width: 50,
              height: 50
            },
            clickable: true
          }, {
            id: 2,
            iconPath: '/images/return_to_center.png',
            position: {
              left: _this.data.mediaInfo.screenWidth - 60,
              top: _this.data.mediaInfo.screenHeight / 2 - 100 + 30,
              width: 50,
              height: 50
            },
            clickable: true
          }],
          mapHeight: (_this.data.mediaInfo.screenHeight - 114) + 'px;'
        });

        _this.loadAroundSellers(_this, 0, lng, lat)
      }
    });

    _this.mapCtx = wx.createMapContext('map');
  },
  onShow: function () {},
  onHide: function () {},
  onUnload: function () {},
  onPullDownRefresh: function () {},
  onReachBottom: function () {},
  onShareAppMessage: function () {},
  listAllCity() {
    let _this = this;
    req.request(api.getAllCity, {}, function(res) {
      let data = res.data, picker_values = [];
      for(let i in data) {
        picker_values.push(data[i].name);
      }
      _this.setData({ picker_values: picker_values })
    })
  },
  loadAroundSellers(_this, range, lng, lat) {
    req.request(
      api.getUserAroundSellers,
      {
        'method': 'POST',
        'data': {
          'lng': lng,
          'lat': lat,
          'city': range
        }
      },
      function (res) {
        var result = res.data,
          markers = [];

        if (result.status == -1) {
          wx.hideLoading();
          wx.showToast({
            title: result.msg,
            icon: 'none',
            duration: 4000
          })
        } else {
          var sellers = result.results
          for (var i in sellers) {
            var item = {}
            item['iconPath'] = "../../images/marker.png"
            item['width'] = 40
            item['height'] = 40
            item['id'] = parseInt(sellers[i]['ex_id'])
            item['latitude'] = parseFloat(sellers[i]['ex_lat'])
            item['longitude'] = parseFloat(sellers[i]['ex_lng'])
            markers.push(item);
          }
          _this.setData({longitude: result.lng, latitude: result.lat});
        }
        _this.setData({ markers: markers, picker_checked: result.city })
        wx.hideLoading();
      }
    )
  },
  regionchange(e) {
    this.setData({ focus: false });
  },
  markertap(e) {
    var _this = this,
        id = e.markerId
    this.setData({ focus: false });

    wx.navigateTo({
      url: '/pages/shops/welcome?id=' + id,
    })
  },
  controltap(e) {
    var _this = this,
        id = e.controlId
    _this.setData({ focus: false });
    if(id == 2) {
      _this.moveToLocation();
    }
    if(id == 3) {
      wx.navigateTo({
        url: '/pages/phone/phone',
      })
    }
    if(id == 1) {
      wx.navigateTo({
        url: '/pages/user/index',
      })
    }
  },
  maptap(e) {
    var word = this.data.word != null ? this.data.word : '搜点什么',
        inputed = this.data.word != null ? 'inputed-view' : ''
    this.setData({focus: false, display: 'none', placeholder: word, inputed: inputed });
  },
  clearHolder(e) {
    var val = e.detail.value;
    this.setData({wd: val})
  },
  toSearch() {
    wx.navigateTo({
      url: '/pages/search/list?wd=' + this.data.wd,
    })
  },
  focusInput() {
    var _this = this
    _this.setData({
      toggleLeft: 'left-focus',
      toggleRight: 'right-focus'
    })
    setTimeout(function() {
      _this.setData({ 
        focus: true, display: 'block'
      })
    }, 600)
  },

  //根据搜索框内容进行搜索
  onsearch: function(e) {
    var detail =  e.detail.value;
    var detail = e.detail.value;
    wx.navigateTo({
      url: '/pages/search/list?wd=' + detail
    })
  },
  //搜索框聚焦时触发动画
  onfocus: function(e) {
    
  },


  //搜索框失焦时触发动画
  onblur: function(e) {
    var word = this.data.word != null ? this.data.word : '搜点什么',
        inputed = this.data.word != null ? 'inputed-view' : ''
    this.setData({
      toggleLeft: '',
      toggleRight: '',
      display: 'none',
      placeholder: word, 
      inputed: inputed
    });
  },
  moveToLocation: function() {
    this.mapCtx.moveToLocation();
  },
  bindKeyInput: function(){
      
  },
  //用户选择范围
  selectRange(e) {
    wx.showLoading({
      title: '加载中',
    })
    var _this = this,
        value = e.detail.value,
        picker_values = _this.data.picker_values

     _this.setData({ picker_checked: picker_values[value] })

    _this.loadAroundSellers(_this, picker_values[value], _this.data.longitude, _this.data.latitude)
  }
})